<template>
  <div class="user-manage">
    <!-- 查询区域 -->
    <div class="query-form">
      <el-form :inline="true" :model="queryForm" ref="refQueryForm">
        <el-form-item label="用户ID:" prop="userId">
          <el-input v-model="queryForm.userId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="用户名称:" prop="userName">
          <el-input v-model="queryForm.userName" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="state">
          <el-select v-model="queryForm.state" placeholder="请选择用户状态">
            <el-option label="所有" :value="0"></el-option>
            <el-option label="在职" :value="1"></el-option>
            <el-option label="离职" :value="2"></el-option>
            <el-option label="试用期" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryFormSubmit" v-auth="'user-query'">查询</el-button>
          <el-button @click="restForm('refQueryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="base-table">
      <!-- 表格头部操作区 -->
      <div class="action">
        <el-button type="primary" @click="openUserModel" v-auth="'user-add'">新增用户</el-button>
        <el-button type="danger" @click="patchDeleteUser" v-auth="'user-patch-delete'">批量删除</el-button>
      </div>
      <!-- 用户列表 -->
      <el-table :data="userList" @selection-change="tableSelectionChange">
        <el-table-column type="selection" />
        <el-table-column
          v-for="colum in colums"
          :key="colum.prop"
          :prop="colum.prop"
          :label="colum.label"
          :formatter="colum.formatter"
          :width="colum.width"
        >
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="mini" @click="editUser(scope.row)" v-auth="'user-edit'">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteUser(scope.row)" v-auth="'user-delete'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handlePageNumChange"
      />
    </div>
    <!-- 新增用户弹窗 -->
    <el-dialog :title="action === 'add' ? '新增用户' : '编辑用户'" v-model="showModal" @close="closeModal">
      <el-form :model="userForm" ref="refUserForm" label-width="100px" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" :disabled="action == 'edit'" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="userForm.userEmail" :disabled="action == 'edit'" placeholder="请输入用户邮箱">
            <template #append>@qq.com</template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="userForm.job" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state">
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select v-model="userForm.roleList" placeholder="请选择系统用户角色" multiple style="width: 100%">
            <el-option v-for="role in roleList" :key="role._id" :label="role.roleName" :value="role._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="closeModal">取 消</el-button>
          <el-button type="primary" @click="userModelSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { onMounted, reactive, ref, getCurrentInstance, toRaw } from 'vue';
import utils from '@/utils/utils.js';
export default {
  name: 'User',
  setup() {
    // 上下文对象
    let { ctx } = getCurrentInstance();
    // 查询表单
    const queryForm = reactive({ state: 1, userId: '', userName: '' });
    // 弹框显示对象
    const showModal = ref(false);
    // 新增用户Form对象
    const userForm = reactive({ state: 3 });
    // 定义表单校验规则
    const rules = reactive({
      userName: [{ required: true, message: '请输入用户名称' }],
      userEmail: [{ required: true, message: '请输入用户邮箱' }],
      mobile: [{ pattern: /1[3-9]\d{9}/, message: '请输入正确的手机格式' }],
      deptId: [{ required: true, message: '请选择部门' }],
    });
    // 所有角色列表
    const roleList = ref([]);
    // 所有部门列表
    const deptList = ref([]);
    // 定义用户操作行为
    const action = ref('add');
    // 分页对象
    const pager = reactive({ pageNum: 1, pageSize: 10, total: 0 });
    // 用户数据
    const userList = ref([]);
    // 选中用户ID数组
    const checkdUserIds = ref([]);

    // 定义表格规范
    const colums = reactive([
      { label: '用户ID', prop: 'userId' },
      { label: '用户名', prop: 'userName' },
      { label: '用户邮箱', prop: 'userEmail' },
      {
        label: '用户角色',
        prop: 'role',
        width: 80,
        formatter(row, column, value) {
          return { 0: '管理员', 1: '普通用户' }[value];
        },
      },
      {
        label: '用户状态',
        prop: 'state',
        width: 80,
        formatter(row, column, value) {
          return { 1: '在职', 2: '离职', 3: '试用期' }[value];
        },
      },
      {
        label: '注册时间',
        prop: 'createTime',
        width: 150,
        formatter(row, column, value) {
          return utils.formateDate(new Date(value));
        },
      },
      {
        label: '最后登录时间',
        prop: 'lastLoginTime',
        width: 150,
        formatter(row, column, value) {
          return utils.formateDate(new Date(value));
        },
      },
    ]);

    // 获取用户数据
    const getUserList = async () => {
      let params = { ...queryForm, ...pager };
      let { list, page } = await ctx.$api.getUserList(params);
      userList.value = list;
      pager.total = page.total;
    };
    // 查询表单提交事件
    const queryFormSubmit = () => {
      getUserList();
    };
    // 表单重置事件
    const restForm = (formName) => {
      ctx.$refs[formName].resetFields();
    };
    // 分页事件处理
    const handlePageNumChange = (pageNum) => {
      pager.pageNum = pageNum;
      getUserList();
    };
    // 表格选中事件
    const tableSelectionChange = (list) => {
      checkdUserIds.value = list.map((item) => item.userId);
    };
    // 删除用户
    const deleteUser = async (user) => {
      await ctx.$api.delUser({ userIds: [user.userId] });
      ctx.$message.success('删除成功');
      getUserList();
    };
    // 编辑用户
    const editUser = async (user) => {
      action.value = 'edit';
      showModal.value = true;
      // 防止赋值太快
      ctx.$nextTick(() => {
        // 浅拷贝赋值
        let userEmail = user.userEmail && user.userEmail.split('@')[0];
        Object.assign(userForm, user, { userEmail });
      });
    };
    // 批量删除用户
    const patchDeleteUser = async () => {
      if (checkdUserIds.value.length === 0) {
        ctx.$message.error('请选择要删除的用户');
        return;
      }
      await ctx.$api.delUser({ userIds: checkdUserIds.value });
      ctx.$message.success('删除成功');
      getUserList();
    };
    // 打开新增用户模态框
    const openUserModel = () => {
      action.value = 'add';
      showModal.value = true;
    };
    // 关闭新增用户模态框
    const closeModal = () => {
      showModal.value = false;
      restForm('refUserForm');
    };
    // 获取部门列表
    const getDeptList = async () => {
      let list = await ctx.$api.getDeptList();
      deptList.value = list;
    };
    // 获取角色列表
    const getRoleAllList = async () => {
      let list = await ctx.$api.getRoleAllList();
      roleList.value = list;
    };
    // 新增用户表单提交事件
    const userModelSubmit = () => {
      ctx.$refs.refUserForm.validate(async (valid) => {
        if (valid) {
          let params = toRaw(userForm); // toRaw响应式对象转为普通对象
          params.userEmail += '@qq.com'; // 修改了响应式的数据了  所以需要 toRaw
          params.action = action.value;
          await ctx.$api.userSubmit(params);
          // 善后操作
          showModal.value = false;
          ctx.$message.success(`用户${action.value == 'add' ? '添加' : '编辑'}成功`);
          restForm('refUserForm');
          getUserList();
        }
      });
    };

    onMounted(() => {
      getUserList();
      getDeptList();
      getRoleAllList();
    });

    return {
      queryForm,
      userList,
      colums,
      getUserList,
      pager,
      queryFormSubmit,
      restForm,
      handlePageNumChange,
      deleteUser,
      patchDeleteUser,
      tableSelectionChange,
      showModal,
      userForm,
      roleList,
      deptList,
      action,
      openUserModel,
      closeModal,
      rules,
      getDeptList,
      userModelSubmit,
      getRoleAllList,
      editUser,
    };
  },
};
</script>
<style scoped lang="scss">
.user-manage {
  .query-form {
  }
  .base-table {
  }
}
</style>
